<template>
	<Modal title="更新分组" v-model="modal" :transfer="transfer" :mask-closable="false" @on-ok="update('form')" :loading="loading">
        <IForm :model="form" ref="form" :rules="formRoles">
            <FormItem prop="name">
                <IInput v-model="form.name" size="large" placeholder="分组名称" />
            </FormItem>
        </IForm>
    </Modal>
</template>
<script>
    import {Modal,Form,Input} from 'iview';

	export default{
		components:{
            Modal,
            'IInput' : Input,
            'IForm' : Form,
            'FormItem' : Form.Item,
        },
        props :{
            callback:{
                type: Function,
                required : true,
            },
            transfer:{
                type: Boolean,
                required : true,
                default : false,
            }
        },
        data(){
        	const validateName=(rule , value ,callback)=>{
        		this.Axios.Wechat.Manager.Material.ImageGroup.Check({name:value,id:this.form.id})
                .then(res =>{
                    if(!res) return false;
                    if(!res.data.result){
                    	callback(new Error('分组名已重复'));
                    }
                    callback();
                })
        		
        	};
        	return {
        		modal : false,
        		loading : true,
                form :{
                	id : 0,
                    name : '',
                },
                formRoles: {
                    name: [
                        { required: true, message: '请填写分组名', trigger: 'blur' },
                        { min: 1, max : 6,  message: '分组名1-6个字符', trigger: 'blur' },
                        { validator: validateName, trigger: 'blur'}
                    ],
                }
        	}
        },
        methods :{
        	changeLoading(){
	            this.loading = false;
	            this.$nextTick(() => {
	              this.loading = true;
	            });
	        },
        	update:function(name){
        		this.$refs[name].validate((valid) => {
                    if (!valid) {this.changeLoading();return false;}
                    this.Axios.Wechat.Manager.Material.ImageGroup.Update(this.form)
	                .then(res =>{
	                    if(!res) return false;
	                    if(res.code!=0){
		                	this.changeLoading();
		                }else{
                            this.modal = false;
		                	this.callback();
		                }
	                })

                })
        	}
        },
        watch :{
        	modal:function(bool){
    			if(!bool){
                    this.form.id = '';
                    this.form.name = '';
                }
        	}
        }
	}
</script>